package org.sluggard.tangela.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

public class TokenStore {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String STORE_NAME = "store";
	
	private File file;

	public TokenStore() throws IOException {
		this(null);
	}

	public TokenStore(File file) throws IOException {
		super();
		if(file != null && file.isFile()) {
			this.file = file;
		} else {
			this.file = new File(STORE_NAME);
			if(!this.file.isFile()) {
				this.file.createNewFile();
			}
		}
	}
	
	public Map<String, Token> load() {
		if(file.canRead()) {
			ObjectInputStream ois = null;
			try {
				ois = new ObjectInputStream(new FileInputStream(file));
				return (Map<String, Token>) ois.readObject();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(ois != null) {
					try {
						ois.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return new HashMap<String, Token>();
	}

	public void save(Map<String, Token> map) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(map);
		oos.close();
	}

}

